﻿import time
import os
from loguru import logger
from pyautogui import FailSafeException
from gui.yun_gui import YunGui
from gui.gui_base import GuiBase
import myutils.window_helper as window_helper
from typing import List
from myutils import services_helper
from model.token import TokenType
from myutils import wechat_notify
from model.exception import (
    ParkTokenFatalError,
    ParkTokenFindImageError,
    ParkTokenWechatHwndError,
    ParkTokenTokenParseError,
)
import cv2
import socket
import pyautogui

logger.add(
    sink="./logs/{time:YYYY-MM-DD}.log",
    # format = "{time:HH:mm:ss} {level} {message}",
    level="INFO",
    rotation="00:00",
)


def build_gui_list(config) -> List[GuiBase]:
    """初始化环境"""

    logger.info("检查环境中...")
    fiddler_hwnd = window_helper.find_window_hwnd_first(
        "Progress Telerik Fiddler Classic"
    )
    if not fiddler_hwnd:
        raise ParkTokenFatalError("未找到fiddler窗口")
    else:
        logger.success("找到fiddler窗口")

    window_helper.max_window(fiddler_hwnd)
    pyautogui.hotkey("ctrl", "x")

    wechat_hwnd_list = window_helper.find_window_hwnd_list_by_title("微信")

    wechat_hwnd_list = [
        hwnd for hwnd in wechat_hwnd_list if window_helper.is_valid_wechat_window(hwnd)
    ]

    if not wechat_hwnd_list:
        raise ParkTokenFatalError("未找到微信窗口")
    else:
        logger.info(f"初始化环境:找到{len(wechat_hwnd_list)}个微信窗口")

    gui_list = []

    for wechat_hwnd in wechat_hwnd_list:
        if TokenType.Yun in config["platform_list"]:
            yun_gui = YunGui()
            yun_gui.set_hwnd(wechat_hwnd)
            yun_gui.set_fiddler_hwnd(fiddler_hwnd)
            gui_list.append(yun_gui)

    if not gui_list:
        raise FailSafeException("无可用的GUI,请检查配置文件")

    return gui_list


def start_gui(gui, retry=0):
    try:
        gui.start()
        return True
    except (FailSafeException, ParkTokenFatalError) as e:
        logger.exception(e)
        raise e
    except ParkTokenWechatHwndError as e:
        logger.exception(e)
    except (ParkTokenFindImageError, ParkTokenTokenParseError) as e:
        logger.exception(e)
        if retry < 10:
            logger.error(f"运行出错,第{retry+1}次重试:{repr(e)}")
            start_gui(gui, retry + 1)
        else:
            raise e

    return False


def notify(msg, config, mention_all=False):
    if "notify_list" not in config:
        return
    for url in config["notify_list"]:
        wechat_notify.send(url, f"{socket.gethostname()}:{msg}", mention_all)

def build_config():
    return {
        "platform_list": [TokenType.Yun],
        "round_interval" : 60,
    }

def run():
    try:
        time.sleep(5)
        round = 0
        config = build_config()
        while True:
            logger.info(f"获取到配置: {config}")
            start_time = time.time()
            logger.info(f"第{round + 1}轮开始")
            gui_list = build_gui_list(config)
            success_count = 0
            for gui in gui_list:
                if start_gui(gui):
                    success_count += 1
            total_time = int(time.time() - start_time)
            logger.info(f"第{round + 1}轮结束, 成功{success_count}条, 耗时{total_time}s")
            notify(f"第{round + 1}轮结束, 成功{success_count}条, 耗时{total_time}s", config)
            # window_helper.kill_process_by_name("WeChatAppEx.exe")
            round += 1
            time.sleep(config["round_interval"])
    except Exception as e:
        logger.exception(e)
        try:
            notify(f"运行出错:{repr(e)}", config, True)
        except Exception as e:
            logger.exception(e)

    os.system("pause")
